<template>
  <div class="patrol">
    <van-nav-bar
        left-arrow
        @click-left="onClickLeft"
        title="巡检滤芯更换"
    />
    <div class="uploader-div" style="margin-top: 20px">
      <div class="uploader-text">巡检记录表照片</div>
      <van-uploader v-model="patrolFileList" accept="image/*" :max-count="1" :after-read="afterReadPatrol"
                    :before-delete="beforeDelete"/>

    </div>
    <div class="uploader-div" style="margin-top: 30px;">
      <div class="uploader-text">滤芯更换照片</div>
      <van-uploader v-model="filterEleFileList" accept="image/*" multiple :max-count="2"
                    :after-read="afterReadFilterEle"
                    :before-delete="beforeDelete"/>
      <van-field
          readonly
          clickable
          name="更换时间"
          :value="replaceDate"
          label="更换时间"
          placeholder="点击选择更换日期"
          @click="showCalendar = true"
      />
      <van-calendar v-model="showCalendar" @confirm="onConfirm" :show-confirm="false" type="single"
                    :min-date="minDate" :max-date="maxDate"/>
      <div class="top-btn">
        <van-button type="primary" color="#1e98dc" block round @click="goSave">保存</van-button>
      </div>

    </div>

  </div>
</template>

<script>
import {
  imgUploadBase64,
  machinePatrolAdd,
  machinePatrolDel,
  machinePatrolGet,
  machinePatrolUpdate
} from "@/api/operator";
import {getLocalOpenId} from "@/utils/wxUtil";
import {formatDateNoH} from "@/utils";

export default {
  data() {
    return {
      showCalendar: false,
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2099, 11, 31),
      replaceDate: '',
      machineId: this.$route.query.id,
      patrolFileList: [],
      filterEleFileList: [],
      fileList: []
    };
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    // beforeRead(file, detail) {
    //   let fileType = ['image/jpeg', 'image/png', 'image/bmp']
    //   if (fileType.indexOf(file.type) === -1) {
    //     this.$toast('请上传 jpg、png、bmp 格式图片');
    //     return false;
    //   }
    //   return true;
    // },
    afterReadPatrol(file, detail) {
      if (file.length > 0) {
        file.map((item, index) => {
          item.status = 'uploading'
          item.message = '上传中...'
          this.doUploadImg(item, '1')
        })
      } else {
        file.status = 'uploading'
        file.message = '上传中...'
        this.doUploadImg(file, '1')
      }
    },
    afterReadFilterEle(file, detail) {
      if (file.length > 0) {
        file.map((item, index) => {
          item.status = 'uploading'
          item.message = '上传中...'
          this.doUploadImg(item, '2')
        })
      } else {
        file.status = 'uploading'
        file.message = '上传中...'
        this.doUploadImg(file, '2')
      }
    },
    beforeDelete(file, detail) {
      this.$dialog.confirm({
        title: '删除提示',
        message: '确认要删除该图片？',
      }).then(res => {
        let index = detail.index;
        let obj = this.fileList[index]
        if (obj) {
          let params = {
            id: obj.id
          }
          machinePatrolDel(params).then(res => {
            this.fileList.splice(index, 1)
            if (obj.type === '1') {
              this.patrolFileList.splice(index, 1)
            } else {
              this.filterEleFileList.splice(index, 1)
            }
          }).catch(res => {
          })
        }
      })
      return false
    },
    doUploadImg(file, type) {
      if (file.file.size > 1 * 1048576) { // 超出1M进行压缩，否则不压缩
        this.imageCompress(file.content).then((result) => {
          const params = {
            openId: getLocalOpenId(),
            machineId: this.machineId,
            base64Str: result.split(',')[1],
            type: type
          }
          machinePatrolAdd(params).then(res => {
            file.status = 'done'
            file.message = ''
            let result = {
              id: res.data.id,
              url: res.data.url,
              type: type
            }
            this.fileList.push(result);
          }).catch(res => {
            file.status = 'failed';
            file.message = '上传失败';
          });
        })
      } else {
        const params = {
          openId: getLocalOpenId(),
          machineId: this.machineId,
          base64Str: file.content.split(',')[1],
          type: type,
          name: this.replaceDate
        }
        machinePatrolAdd(params).then(res => {
          file.status = 'done'
          file.message = ''
          let result = {
            id: res.data.id,
            url: res.data.url,
            type: type
          }
          this.fileList.push(result);
        }).catch(res => {
          file.status = 'failed';
          file.message = '上传失败';
        });
      }
    },
    imageCompress(base64) { // 压缩图片
      let Img = new Image()
      let dataURL = ''
      Img.src = base64
      let p = new Promise(function (resolve, reject) {
        Img.onload = function () { // 要先确保图片完整获取到，这是个异步事件
          let canvas = document.createElement('canvas') // 创建canvas元素
          let width = Img.width // 确保canvas的尺寸和图片一样
          let height = Img.height
          // 默认将长宽设置为图片的原始长宽，这样在长宽不超过最大长度时就不需要再处理
          let ratio = width / height
          let maxLength = 1000
          let newHeight = height
          let newWidth = width
          // 在长宽超过最大长度时，按图片长宽比例等比缩小
          if (width > maxLength || height > maxLength) {
            if (width > height) {
              newWidth = maxLength
              newHeight = maxLength / ratio
            } else {
              newWidth = maxLength * ratio
              newHeight = maxLength
            }
          }
          ;
          canvas.width = newWidth
          canvas.height = newHeight
          canvas.getContext('2d').drawImage(Img, 0, 0, newWidth, newHeight) // 将图片绘制到canvas中
          dataURL = canvas.toDataURL('image/jpeg', 0.5) // 转换图片为dataURL
          resolve(dataURL)
        }
      })
      return p
    },
    onConfirm(date) {
      date = formatDateNoH(date)
      this.replaceDate = date
      this.showCalendar = false
    },
    goSave(){
      let params={
        machineId: this.machineId,
        replaceDateStr: this.replaceDate
      }
      machinePatrolUpdate(params).then(res=>{
        this.$toast.success('保存成功');
      })
    }
  },
  mounted() {
    let params = {
      id: this.machineId
    }
    machinePatrolGet(params).then(res => {
      if (res.data !== undefined && res.data.length > 0) {
        res.data.forEach((item, index, arr) => {
          let obj = {
            id: item.id,
            url: item.url,
            type: item.type
          }
          if (item.type === '1') {
            this.patrolFileList.push(obj)
          } else {
            this.filterEleFileList.push(obj)
          }
          this.fileList.push(obj)

          if(!this.replaceDate){
            if(item.replaceDate){
              let dateStr = formatDateNoH(item.replaceDate);
              this.replaceDate = dateStr
            }
          }

        })
      }
    })
  }
}
</script>

<style lang="less" scoped>
.patrol {
  text-align: center;

  .uploader-div {
    margin-top: 10px;
    padding: 5px;

    .uploader-text {
      padding: 10px;
    }
    .top-btn{
      text-align: center;
      margin-left: 25%;
      padding-top: 15px;
      width: 50%;
    }
  }
}

</style>
